/*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~
 *  global var
 *~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*/
var NONE_MODE = 0;
var INPUT_MODE = 1;
var SELECTION_MODE = 2;
var current_mode = NONE_MODE;
var input_method_set = [];
var current_im_idx = 0;
var main_panel_min_width = 900; // px
var main_panel_min_height = 620; // px
var gears;
var store;
var syncIdleTimeout = 10; // seconds
var syncLabel = 'connection_status'; 
var captureTimeout = 10; // seconds
var clip;
/*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~
 *  UI functions
 *~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*/
function show_input_panel() {
  arr = im.getInput();
  h = '';
  for (i=0; i<arr.length; i++) {
    h += '<span class="input-char">'+arr[i]+'</span>';
  }
  $('#input-panel').html(h);
}
function show_option_panel() {
  arr = im.getCurrentOption();
  if (arr.length > 0) {
    h = '';
    //h = '';
    for (i=0; i<arr.length; i++) {
      number = (i+1) % im.pagesize;
      h += '<span class="option-char" alt="'+arr[i]+'"><sup class="option-char-index" style="visibility: hidden">'+number+' </sup>'+arr[i]+'</span>';
    }
    //h += '';
    $('#option-panel').html(h);
    
    // add selection interaction
    $('.option-char').click(function () {
      // logging($(this).attr('alt'));
      pre_value = $('#char-result').val();
      $('#char-result').val(pre_value + $(this).attr('alt'));
      im.selectResult($(this).attr('alt'));
      if (im.getName() == 'StrokeIM') {
        if (im.getContext()['option'].length==0) {
          im.resetContext();
          current_mode = NONE_MODE;
        } else {
          current_mode = INPUT_MODE;
        }
      } else if (im.getName() == 'SymbolIM') {
        ;
      } else {
        im.resetContext();
        current_mode = NONE_MODE;
      }
      show_context();
    }).hover(function () {
      $(this).addClass('option-char-border');
    }, function () {
      $(this).removeClass('option-char-border');
    });
  }
  if (im.hasPreviousPage()) {
    $('#previous-page-sign').unbind('click');
    $('#previous-page-sign').css({'visibility':'visible'}).click(function () {
      im.previousPage();
      show_context();    
    }).hover(function () {$(this).addClass('hand-pointer');}, function () {$(this).removeClass('hand-pointer');});
  } else {
    $('#previous-page-sign').css({'visibility':'hidden'});
  }
  if (im.hasNextPage()) {
    $('#next-page-sign').unbind('click');
    $('#next-page-sign').css({'visibility':'visible'}).click(function () {
      im.nextPage();
      show_context();    
    }).hover(function () {$(this).addClass('hand-pointer');}, function () {$(this).removeClass('hand-pointer');});
  } else {
    $('#next-page-sign').css({'visibility':'hidden'});
  }
}

function show_context() {
  //logging('current_mode: '+current_mode);
  // logging('input: '+im.getContext()['input']);
  //logging('option: ' + im.getContext()['option']);
  //logging('currentpage: '+im.getContext()['currentpage']);
  //logging('has previous: '+im.hasPreviousPage());
  //logging('has next: '+im.hasNextPage());
  $('#input-panel').html('');
  $('#option-panel').html('');
  
  switch (current_mode) {
  case NONE_MODE:
    if ($('#panel-container').is(':visible')) {
      $('#panel-container').hide('drop', {direction: "down", easing: "easeOutQuint"}, 200);;
    }
    break;
  case INPUT_MODE:
    if ($('#panel-container').css('display') == 'none') {
      $('#panel-container').show('drop', {direction: "down", easing: "easeOutQuint"}, 200);
    }
    show_input_panel();
    show_option_panel();
    break;
  case SELECTION_MODE:
    show_input_panel();
    show_option_panel();
    $('.option-char-index').css({'visibility': 'visible'});
    break;
  default:
    ;
  }
}

function show_nav_detail_window(s, h, w) { // s - string, content, h - window height
  hide_nav_detail_window();
  if (h) {
      $('#nav-detail-window').height(h);
      $('#nav-detail-window-background').height(h);
  }
  if (w) {
      $('#nav-detail-window').width(w);
      $('#nav-detail-window-background').width(w);  
  }
  $('#nav-detail-window-content').html(s);
  $('#nav-detail-window').css('display', 'block');
  $('#nav-detail-window-background').css('display', 'block');
}

function hide_nav_detail_window() {
  $('#nav-detail-window').css('display', 'none');
  $('#nav-detail-window-background').css('display', 'none');
}

function enable_offline_mode() {
  if (!gears.isCaptured()) {
    gears.capture();
  }
  else {
    return;
  }
  $('#nav-onoffline').html('正在处理...');
  hide_nav_detail_window();
  cookie_enable_offline();
  
  // gears bug, no notification about capture successfully. 
  // ugly solution, a schedule timer.
  $().everyTime(captureTimeout*1000, 'capture_timer', function() {
    //logging('capture_timer :'+gears.isCaptured());
    if (gears.isCaptured()) {
      $().stopTime('capture_timer');
      if ($('#nav-onoffline').html() == '正在处理...') {
        onappupdate(gears.getCurrentVersion());
      }
    }
  })
}

function disable_offline_mode() {
  gears.uncapture();
  $('#nav-onoffline').html('开启离线功能');
  hide_nav_detail_window();
  cookie_disable_offline();
}

function notify_user_update_app() {
  if (1 == $('#copyright-panel span').length) {
    $('#copyright-panel span').after('<span>检测到新版本，<a href="/">请刷新</a></span>');
  }
}

function initial_events() {
  panel_arr = ['button-delete', 'button-ok', 'previous-page', 'next-page'];
  for (i=0; i<panel_arr.length; i++) {
    $('#'+panel_arr[i]).hover(function () {
      $(this).addClass('hand-pointer');
      //$(this).css({'background-image':'url(/ezkeypad/media/key_fw.png)'});
      if (undefined != $(this).css('background-position')) {
        position_str = $(this).css('background-position');
        x_offset_str = position_str.split(' ')[0];
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        position_str = position_str.substr(x_offset_str.length);
        x_offset = parseInt(x_offset_str)+210;
        position_str = x_offset+position_str;
        $(this).css({'background-position': position_str});
      } else {
        x_offset_str = $(this).css('background-position-x');
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        x_offset = parseInt(x_offset_str)+210;
        $(this).css({'background-position-x': x_offset+'px'});      
      }
    }, function () {
      $(this).removeClass('hand-pointer');
      //$(this).css({'background-image':'url(/ezkeypad/media/keypad.png)'});
      if (undefined != $(this).css('background-position')) {
        position_str = $(this).css('background-position');
        x_offset_str = position_str.split(' ')[0];
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        position_str = position_str.substr(x_offset_str.length);
        x_offset = parseInt(x_offset_str)-210;
        position_str = x_offset+position_str;
        $(this).css({'background-position': position_str});      
      } else {
        x_offset_str = $(this).css('background-position-x');
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        x_offset = parseInt(x_offset_str)-210;
        $(this).css({'background-position-x': x_offset+'px'});        
      }
    });
  }
  
  sel_arr = ['sel-pinyin', 'sel-stroke', 'sel-upperchar', 
    'sel-lowerchar', 'sel-number'];
  for (i=0; i<sel_arr.length; i++) {
    $('#'+sel_arr[i]).click(function () {
      //logging($(this).attr('id'));
      ;
    }).hover(function () {
      $(this).addClass('hand-pointer');
    }, function () {
      $(this).removeClass('hand-pointer');
    });
  }
  
  button_arr = ['button1', 'button2', 'button3', 'button4', 'button5', 'button6', 
    'button7', 'button8', 'button9', 'button0', 'buttonstar', 'buttonwell'];
  for (i=0; i<button_arr.length; i++) {
    $('#'+button_arr[i]).click(function () {
      if (current_mode == SELECTION_MODE) {
        idx = parseInt($(this).attr('id').substr(6));
        if (isNaN(idx) == false) {
          arr = im.getCurrentOption();
          idx -= 1;
          if (idx<0) {idx += im.pagesize};
          if (undefined != arr[idx]) {
            pre_value = $('#char-result').val();
            $('#char-result').val(pre_value + arr[idx]);
            im.selectResult(arr[idx]);
            if (im.getName() == 'StrokeIM') {
              if (im.getContext()['option'].length==0) {
                im.resetContext();
                current_mode = NONE_MODE;
              } else {
                current_mode = INPUT_MODE;
              }
            } else if (im.getName() == 'SymbolIM') {
              ;
            } else {
              im.resetContext();
              current_mode = NONE_MODE;
            }
          }
        }
      } else {
        im.processInput($(this).attr('id'));
        im.updateContext();
        c = im.getContext()
        im_name = im.getName()
        if ((im_name == 'StrokeIM') || (im_name == 'UpperCharIM') || (im_name == 'LowerCharIM')) {
          if (im.getInput().length != 0) {
            current_mode = INPUT_MODE;
          }
        } else if (im_name == 'NumberIM') {
          pre_value = $('#char-result').val();
          $('#char-result').val(pre_value + c['result']);
        } else if(im_name == 'SymbolIM') {
          current_mode = INPUT_MODE;
        } else {
          // do nothing.
          ;
        }
      }
      show_context();
    }).hover(function () {
      $(this).addClass('hand-pointer');
      //$(this).css({'background-image':'url(/ezkeypad/media/key_fw.png)'});
      if (undefined != $(this).css('background-position')) {
        position_str = $(this).css('background-position');
        x_offset_str = position_str.split(' ')[0];
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        position_str = position_str.substr(x_offset_str.length);
        x_offset = parseInt(x_offset_str)+210;
        position_str = x_offset+position_str;
        $(this).css({'background-position': position_str});
      } else {
        x_offset_str = $(this).css('background-position-x');
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        x_offset = parseInt(x_offset_str)+210;
        $(this).css({'background-position-x': x_offset+'px'});
      }
    }, function () {
      $(this).removeClass('hand-pointer');
      //$(this).css({'background-image':'url(/ezkeypad/media/keypad.png)'});
      if (undefined != $(this).css('background-position')) {
        position_str = $(this).css('background-position');
        x_offset_str = position_str.split(' ')[0];
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        position_str = position_str.substr(x_offset_str.length);
        x_offset = parseInt(x_offset_str)-210;
        position_str = x_offset+position_str;
        $(this).css({'background-position': position_str});
      } else {
        x_offset_str = $(this).css('background-position-x');
        x_offset_str = x_offset_str.substr(0, x_offset_str.length-2);
        x_offset = parseInt(x_offset_str)-210;
        $(this).css({'background-position-x': x_offset+'px'});
      }
    });
  }
  
  $('#buttonstar').unbind('click').click(function () {
    current_im_idx = (current_im_idx+1) % input_method_set.length;
    $.cookie('c_current_im_idx', current_im_idx, {expires: 30});
    im = input_method_set[current_im_idx];
    $('#im-sign').html(im.getOfficialName());
    im.resetContext();
    if (input_method_set[current_im_idx].getName() == 'SymbolIM') {
      current_mode = INPUT_MODE;
      im.updateContext();
    } else {
      current_mode = NONE_MODE;
    }
    show_context();
    //logging(im.getName());
  });
  
  $('#buttonwell').unbind('click').click(function () {
    pre_val = $('#char-result').val();
    $('#char-result').val(pre_val+' ');
  });
  
  
  $('#previous-page').click(function () {
    switch (current_mode) {
    case NONE_MODE:
      break;
    case INPUT_MODE:
    case SELECTION_MODE:
      im.previousPage();
      break;
    default:
      ;
    }
    show_context();
  });
  $('#next-page').click(function () {
    switch (current_mode) {
    case NONE_MODE:
      break;
    case INPUT_MODE:
    case SELECTION_MODE:
      im.nextPage();
      break;
    default:
      ;
    }
    show_context();
  });
  $('#button-ok').click(function () {
    switch (current_mode) {
    case NONE_MODE:
      break;
    case INPUT_MODE:
      current_mode = SELECTION_MODE;
      break;
    case SELECTION_MODE:
      break;
    default:
      ;
    }
    show_context();
  });
  $('#button-delete').click(function() {
    switch (current_mode) {
    case NONE_MODE:
      // delete the last char of result;
      if (0 != $('#char-result').val().length) {
        s = $('#char-result').val();
        $('#char-result').val(s.substr(0, s.length-1));
      }
      break;
    case INPUT_MODE:
      if (im.getName() != 'SymbolIM') {
        if (im.getContext()['input'].length > 1) {
          im.deleteInput();
          im.updateContext();
        } else {
          im.deleteInput();
          im.updateContext();
          current_mode = NONE_MODE;
        }
      } else {
        // delete symbols in result textarea
        if (0 != $('#char-result').val().length) {
          s = $('#char-result').val();
          $('#char-result').val(s.substr(0, s.length-1));
        }        
      }
      break;
    case SELECTION_MODE:
      current_mode = INPUT_MODE;
      break;
    default:
      ;
    }
    show_context();
  });
  $('#copy-result').hover(function () {
    $(this).addClass('hand-pointer');
    $(this).css({'background-position':'-108px 0px'});
    util_copy_to_clipboard($('#char-result').val());
  }, function () {
    $(this).removeClass('hand-pointer');
    $(this).css({'background-position':'-52px 0px'});
  }).click(function () {
    util_copy_to_clipboard($('#char-result').val());
  });
  $('#empty-result').hover(function () {
    $(this).addClass('hand-pointer');
    $(this).css({'background-position':'-80px 0px'});
  }, function () {
    $(this).removeClass('hand-pointer');
    $(this).css({'background-position':'-24px 0px'});
  }).click(function () {
    $('#char-result').val('');
  });
  
  $('#tip-notify-label').toggle(function () {
    $('#tip-notify').attr('checked', true);
  }, function () {
    $('#tip-notify').attr('checked', false);
  }).hover(function () {
    $(this).addClass('hand-pointer');
  }, function () {
    $(this).removeClass('hand-pointer');
  });
  
  $('#tip-start-service').click(function () {
    $('#model-panel').css({'display': 'none'});
    $('#tip-panel').css({'display': 'none'});
    
    if ($('#tip-notify').attr('checked') == true) {
      $.cookie('c_notify_next_time', '0', {expires: 30});
    } else {
      $.cookie('c_notify_next_time', '1', {expires: 30});
    }
  });
  $('#tip-close-window').click(function () {
    util_close_window();
  });
  
  $('#nav-connection').hover(function() {
    if(store.isOnline) {
      s = '当前状态：<span style="color: green;"><b>在线</b></span>';
    } else {
      s = '当前状态：<span style="color: red;"><b>离线</b></span>';
    }
    show_nav_detail_window(s, 15, 180);
  }, function() {});
  
  $('#nav-onoffline').click(function() {
    s = '<p>当前状态：';
    if (gears.hasGears) {
      if (gears.isCaptured()) {
        s += '<span style="color: green;"><b>已启用离线模式</b></span></p>';
        s += '<p>使用离线模式，可以保证电脑在离线状态下仍然可以方便的使用<b>“简单输入”</b></p>';
        s += '<p><a href="javascript:disable_offline_mode();">>>> 关闭离线模式</a></p>'
      } else {
        s += '<span style="color: red;"><b>未启用离线模式</b></span></p>';
        s += '<p>使用离线模式，可以保证电脑在离线状态下仍然可以方便的使用<b>“简单输入”</b></p>';
        s += '<p><a href="javascript:enable_offline_mode()">>>> 启用离线模式</a></p>'
      }
    } else {
      s += '<span style="color: red;"><b>未启用离线模式</b></span></p>';
      s += '<p>使用离线模式，可以保证电脑在离线状态下仍然可以方便的使用<b>“简单输入”</b></p>'    
      s += '<p><a href="javascript: util_install_gears();cookie_enable_offline();">>>> 启用离线模式</a></p>'
    }
    
    show_nav_detail_window(s, 80, 260);
  });
  
  
  $('#nav-favorite').click(function() {
    s = '<p>将<b>“简单输入”</b>放入收藏夹，下次可直接从收藏夹启动。<br></p><p><a href="javascript:util_add_favorite()">>>> 添加</a></p>';
    show_nav_detail_window(s, 60, 200);
  });
  
  $('#nav-shortcut').click(function() {
    s = '<p>将<b>“简单输入”</b>的快捷方式放至桌面，下次可直接双击桌面图标启动。</p>';
    if (gears.hasGears) {
      s += '<p><a href="javascript: gears.createDesktopShortcut()">>>> 添加</a></p>';
    } else {
      s += '<p><a href="javascript: util_install_gears()">>>> 添加</a></p>';
    }
    show_nav_detail_window(s, 60, 220);
  });
  
  $('#nav-detail-window-close').click(function() {
    hide_nav_detail_window();
  });
  
  $(window).resize(function () {
    $('#main-panel').css({'height':Math.max(util_get_screen_height(), main_panel_min_height), 
      'width':Math.max(util_get_screen_width(), main_panel_min_width)});
    $('#model-panel').css({'height':util_get_screen_height(), 'width':util_get_screen_width()});
  });
}

function initial_style() {
  $('#panel-container').css({'display': 'none'});
  $('body').css({'background-color':'#bbc2ee'});
  $('#main-panel').css({'height':Math.max(util_get_screen_height(), main_panel_min_height)+'px', 
    'width':Math.max(util_get_screen_width(), main_panel_min_width)+'px'});
    
  $('#char-result').val('');
}

function show_tip_window() {
  // check environment
  //$.browser.msie = false;
  if (($.browser.safari) || ($.browser.mozilla) || ($.browser.msie)) {
    $('#tip-env-check').html('<p><span style="color: green;">运行环境检测：通过</span></p>');
    $('#tip-start-service').attr('disabled', false);
  } else {
    $('#tip-notify-panel').css({'display':'none'});
    $('#tip-start-service').attr('disabled', true);
    $('#tip-env-check').html('<p><span style="color: red;">运行环境检测：未通过，请安装：<a href="http://is.gd/v1rp" target="_blank">火狐浏览器</a> 或者 <a href="http://is.gd/v1rb" target="_blank">谷歌浏览器</a> 或者 <a href="http://is.gd/wVgb" target="_blank">IE7浏览器</a></span></p>');
  }
  
  // TODO: check cookies. 
  if ((null == $.cookie('c_notify_next_time')) || ('1' == $.cookie('c_notify_next_time'))) {
    $('#tip-notify').attr('checked', false);
    // set model-pantl style
    $('#model-panel').css({'height':util_get_screen_height(), 
      'width':util_get_screen_width(), 
      'display':'block'});  
    // set tip window style

    $('#tip-panel').css({'height':'360px', 
      'width':'600px', 
      'display':'block',
      'top':(util_get_screen_height()-360)/2+'px',
      'left':(util_get_screen_width()-600)/2+'px'});
  }
}

function initial_im() {
  input_method_set = [
    new StrokeIM(),
    new UpperCharIM(),
    new LowerCharIM(),
    new NumberIM(),
    new SymbolIM()
  ];
  
  if (null == $.cookie('c_current_im_idx')) {
    current_im_idx = 0;
  } else {
    current_im_idx = $.cookie('c_current_im_idx') % input_method_set.length;
  }
  
  im = input_method_set[current_im_idx];
  $('#im-sign').html(im.getOfficialName());
  
  if (input_method_set[current_im_idx].getName() == 'SymbolIM') {
    current_mode = INPUT_MODE;
    im.updateContext();
    show_context();
  } else {
    current_mode = NONE_MODE;
  }
}
function initial_clipboard() {
  ZeroClipboard.setMoviePath('/ezkeypad/media/ZeroClipboard.swf');
  clip = new ZeroClipboard.Client();
  clip.setHandCursor(true);
  
  clip.addEventListener('mouseOver', function(client) {clip.setText($('#char-result').val());});
  //clip.addEventListener('onMouseDown', function(client) {util_copy_to_clipboard($('#copy-result').val());});
  //clip.addEventListener('complete', function(client, text) {alert(text);});
  
  clip.glue('copy-result');
}

function initial_service() {
  // initial style
  initial_style();
  // initial button event
  initial_events();
  // initial input method
  initial_im();
  // initial ZeroClipboard
  initial_clipboard();
  
  gears = new Gears(onappupdate);
  if (gears.isCaptured()) {
    $('#nav-onoffline').html('关闭离线功能');
  }
  
  // check user whether enable offline mode
  check_enable_offline_mode();
  
  store = new DataStore(onsync);
  show_tip_window();
  $().everyTime(syncIdleTimeout*1000, syncLabel, function() {
    store.sync();
  }); 
  store.sync(); // fire the first time sync
}

function cookie_enable_offline() {
  $.cookie('c_cookie_record_offline', 1, {expires: 3000});
}
function cookie_disable_offline() {
  $.cookie('c_cookie_record_offline', 0, {expires: 3000});  
}
function check_enable_offline_mode() {
  //logging('check_enable_offline_mode: '+$.cookie('c_cookie_record_offline'));
  if (!$.cookie('c_cookie_record_offline')) {
    $.cookie('c_cookie_record_offline', 0, {expires: 3000});  
  } else {
    if (gears.hasGears && !gears.isCaptured() && ('1' == $.cookie('c_cookie_record_offline'))) {
      //logging('enable offline mode');
      enable_offline_mode();
    }
  }
}

/*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~
 *  Callback functions
 *~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*~-*/
function onappupdate(s) {
  // logging('onappupdate: '+s);
  if (s) {
    if ($('#nav-onoffline').html() == '正在处理...') {
      $('#nav-onoffline').html('关闭离线功能');
    } else if ($('#nav-onoffline').html() == '关闭离线功能') {
      notify_user_update_app();
    } else if ($('#nav-onoffline').html() == '开启离线功能') {
      logging('onappupdate: error status');
    } else {
      logging('onappupdate: unknown status');
    }
  }
}

function onsync(s) {
  // logging('onsync: '+s);
  // empty online/offline style
  $('#nav-connection').removeClass('nav-connection-online');
  $('#nav-connection').removeClass('nav-connection-offline');
  if (s) {
    $('#nav-connection').addClass('nav-connection-online');
  } else {
    $('#nav-connection').addClass('nav-connection-offline');
  }
}